package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.business.service.IWsdLeavesService;
import com.ruoyi.business.service.IWsdRefundTransactionsService;
import com.ruoyi.business.service.IWsdRoleClassService;
import com.ruoyi.business.service.IWsdStudentsService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.WsdStudents;
import com.ruoyi.common.core.domain.vo.AgencyMattersVO;
import com.ruoyi.common.core.domain.vo.ChartDataVO;
import com.ruoyi.common.core.domain.vo.leaveNumberVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * 首页数据汇总
 *
 * @author ruoyi
 * @date 2024-04-15
 */
@RestController
@RequestMapping("wsd_summarization")
public class WsdSummarizationController extends BaseController {

    @Autowired
    private IWsdLeavesService wsdLeavesService;

    @Autowired
    private IWsdRoleClassService wsdRoleClassService;

    @Autowired
    private IWsdStudentsService wsdStudentsService;
    @Autowired
    private IWsdRefundTransactionsService wsdRefundTransactionsService;


    /**
     * 获取周月年的柱状图
     */
    @GetMapping(value = "/LeaveStatisticsProvider")
    public AjaxResult LeaveStatisticsProvider(@RequestParam Optional<Integer> year, @RequestParam Optional<Integer> month, @RequestParam String statisticType) {
        ChartDataVO chartDataVO;
        Long schoolId = null;
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()){
            schoolId = user.getSchoolId(); // 获取用户的学校ID
        }
        // 根据统计类型调用不同的方法
        switch (statisticType.toUpperCase()) {
            case "YEAR":
                chartDataVO = wsdLeavesService.queryYearlyLeaveCounts(schoolId);
                break;
            case "MONTH":
                chartDataVO = wsdLeavesService.queryMonthlyLeaveCounts(schoolId,year, month);
                break;
            case "WEEK":
                chartDataVO = wsdLeavesService.queryWeeklyLeaveCounts(schoolId);
                break;
            default:
                return AjaxResult.error("无效的统计类型参数");
        }
        return AjaxResult.success(chartDataVO); // 返回封装好的Ajax结果
    }

    /**
     * 获取退款情况曲线图
     */
    @GetMapping(value = "/returnLineChart")
    public AjaxResult returnLineChart(@RequestParam String statisticType) {
        ChartDataVO result;
        Long schoolId = null;
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()){
            schoolId = user.getSchoolId(); // 获取用户的学校ID
        }
        switch (statisticType) {
            case "YEAR":
                // 按月查询当前年份
                result = wsdRefundTransactionsService.getTotalFeeByYear(schoolId);
                break;
            case "MONTH":
                // 按年查询当前年份
                result = wsdRefundTransactionsService.getTotalFeeByMonth(schoolId);
                break;
            case "WEEK":
                // 获取当前日期
                LocalDate now = LocalDate.now();

                // 获取本周周一的日期
                LocalDate startOfWeek = now.with( TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
                LocalTime startTime = LocalTime.MIN; // 一天的开始时间（00:00）

                // 获取本周周日的日期
                LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(java.time.DayOfWeek.SUNDAY));
                LocalTime endTime = LocalTime.MAX; // 一天的结束时间（23:59:59.999999999）

                // 结合日期和时间创建LocalDateTime对象
                LocalDateTime startDate = LocalDateTime.of(startOfWeek, startTime); // 本周周一的开始时间
                LocalDateTime endDate = LocalDateTime.of(endOfWeek, endTime); // 本周周日的结束时间

                // 定义日期时间格式器
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

                // 将LocalDateTime转换为指定格式的字符串
                String startDateStr = startDate.format(formatter);
                String endDateStr = endDate.format(formatter);
                result = wsdRefundTransactionsService.getTotalFeeByDateRange(startDateStr, endDateStr,schoolId);
                break;
            default:
                return AjaxResult.error("无效的类型。允许的值为 月, 年, 时间区间");
        }
        return AjaxResult.success(result);
    }

    /**
     * 获取今天的请假情况.订餐情况
     * @return
     */

    @GetMapping(value = "/todayLeaveStatistics")
    public AjaxResult getTodayLeaveStatistics() {
        SysUser user = getLoginUser().getUser();
        if (user.isAdmin()){
            //admin账号
            return AjaxResult.success(wsdLeavesService.todayLeaveStatus(null));
        }
        Long schoolId = user.getSchoolId();
        if (schoolId == null){
            return AjaxResult.error("学校ID为空,请联系管理员");
        }
        leaveNumberVO leaveNumberVO = wsdLeavesService.todayLeaveStatus(schoolId);
        return  AjaxResult.success(leaveNumberVO);
    }

    /**
     * 代办事项显示
     * @return
     */
    @GetMapping(value = "/agencyMatters")
    public AjaxResult agencyMatters() {
        Long schoolId = null;
        SysUser user = getLoginUser().getUser();
        if (!user.isAdmin()) {
            schoolId = user.getSchoolId();
        }
        AgencyMattersVO agencyMattersVO = wsdLeavesService.agencyMatters(schoolId);
        return AjaxResult.success(agencyMattersVO);
    }

    /**
     * 全班,全校人数统计
     * @return
     */
    @GetMapping(value = "/populationStatistics")
    public AjaxResult populationStatistics() {
        // Long[] classIds = wsdRoleClassService.queryList().getClassIds();
        // Long count = wsdStudentsService.populationStatistics(classIds);
        SysUser user = getLoginUser().getUser();
        Long schoolId = null;
        if (!user.isAdmin()){
            schoolId = user.getSchoolId();
        }
        LambdaQueryWrapper<WsdStudents> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WsdStudents::getSchoolId,schoolId);
        long count = wsdStudentsService.count(wrapper);
        return AjaxResult.success(count);
    }

}
